第 2 课:LLM 作为决策引擎(Decision Engine)
你需要掌握:
- 1.1 如何让 LLM 做“推理 + 决策”
- 1.2 Prompt 架构(System Prompt、Role Prompt、Loop Prompt)
- 1.3 如何让 LLM 可控(避免幻觉)
- 1.4 LLM 的三种模式:
- 纯文本聊天模型(OpenAI GPT、Llama)
- 工具调用模型(function-calling 模式)
- 思维链模型(CoT)
- 1.5 决策类 Prompt 的结构化格式:
示例(工程化格式):
Thought:
Action:
Action Input:
- 1.6 如何让模型“只输出 JSON”
- 1.7 如何限制模型不跑偏(Guardrails + Validators)
- 1.8 推理深度控制(max_steps、deliberate_thinking)
(一)如何让 LLM 做“推理 + 决策”
在 Agent 系统里,LLM 不再是“回答问题的聊天机器人”,而是一个 Policy(策略函数):
输入:当前状态 state(含目标、历史、工具可用性、约束) 输出:下一步动作 action(包括 finish / tool_call / ask_user / replan)
后面所有模块(ReAct / Planner / State Machine)都建立在这个认知之上。
工程上,你必须把“决策”变成可解析的结构化输出,而不是自然语言随便说。
决策输出的两种主流形态
- 形态 A:Action JSON(推荐) 适合工程解析、状态机、工具路由
- 形态 B:Thought/Action/Obs(教学友好) 适合调试,但不如 JSON 稳
同时,你还要定义这个 agent 可以做的所有决策和动作,这称为 决策空间
必须把动作空间写进 system prompt,是可控性的第一步。
典型 Agent 最小动作集合:
finish:输出最终回答tool_call:调用某个工具ask_user:信息不足,向用户提问replan:当前策略失败,重做计划
(二)Prompt 架构
工程上建议你把 prompt 分成三层(System / Role / Loop),并且代码里明确分离,便于维护、A/B test、版本化。
核心目的只有三点:
- 可控性:System 里放“硬规则”,避免模型跑偏。
- 可维护性:Role 变化频繁;Loop 每轮变化更频繁。分层能减少改动面。
- 可实验性:A/B test 只替换某一层(通常是 Role 或 System 的某个片段),其余不动,才能对比出“因果效果”。
1. System Prompt
System 是“宪法”,原则是:只放长期稳定且强约束的内容。
包含:
- 允许的动作集合(action space)
- 输出必须为 JSON(schema)
- 禁止输出推理过程(如果你要)
- 失败时的 fallback(例如:JSON 解析失败如何纠正)
- 工具使用原则(“没有 observation 不得引用工具结果”)
建议你把 System 写成“规格文档式”的 Prompt:
- 明确 schema
- 明确 allowed values
- 明确 error policy
示例(决策引擎 System):
You are an agent decision engine.
Output MUST be exactly one valid JSON object. No markdown, no extra text.
Allowed actions: ["finish","tool_call","ask_user","replan"].
Schema:
{
"action": "...",
"tool": "string|null",
"tool_input": "object|null",
"final": "string|null"
}
Rules:
- Never claim tool results without an Observation.
- If output is not valid JSON, self-correct and output valid JSON only.
- Be concise.
2. Role Prompt
Role 是“岗位说明书”(可变:任务角色与偏好),随场景变化。放:
- 任务类型(网页调研 / 代码生成 / 竞品分析 / 运营文案等)
- 风格偏好(简短、bullet、严格引用等)
- 质量标准(必须给出可执行步骤、必须给出风险提示等)
Role 的关键:同一系统规则下,切换岗位能力。
示例:
- “你是网页调研 agent,必须给出来源链接/引用”
- “你是代码审查 agent,优先指出安全风险”
- “你是数据分析 agent,输出要包含可复现步骤”
例如:
- “你是一个网页调研 agent”
- “你输出要简短”
- “你必须引用来源(如果有 web 工具)”